var startTime=echartUtil.GetDateStr(-90);
var endTime=echartUtil.GetDateStr(0);

var tableReport;
var tableFeed;
var tableIn;
//相关业务逻辑
$(function(){
	reportP.pageBind();
	reportP.reportBind();
	reportP.getAllSearchWhere();
	reportP.getAllMachining();
	reportP.getWorkshopName();
//	reportP.getMyRoportNotApprovalData();
	$("#startTime").val(startTime);
	$("#endTime").val(endTime);
});


var reportP={//页面总变量
		orderPamar:['companyOrderId','factoryId','coustomId','coustomOrderId','orderId'],
		orderList:[],
		pageBind:function(){
			/**
			 * 查询我的报工记录按钮
			 */
			$("#querryReportBtn").bind("click",function(){
				var object=new Object;
				for(var i=0;i<reportP.orderPamar.length;i++){
					object[reportP.orderPamar[i]]=$("#"+reportP.orderPamar[i]).val();
				}
				object.machining=$("#machining").val();
				object.status=$("#status option:selected").val();
				object.startTime=$("#startTime").val();
				object.endTime=$("#endTime").val();
				object.workShopId=$("#workshopName").val();
				console.log(object);
				reportP.getMyRoportNotApprovalData(object);
			});
			
			for(var i=0;i<reportP.orderPamar.length;i++){
				$("#"+reportP.orderPamar[i]).bind("change",function(){
					filterInput.filterView("",reportP.orderPamar,reportP.orderList);
				});
			}
			
//			批量编辑
			$(".reportAll").bind("click",function(){
				$("#myReport .eidtReport").hide();
				$("#myReport .deleteReport").hide();
				$("#myReport .check").show();
			});
			
//			关闭模态框清除数据
			$("#reportModelColse").bind("click",function(){
				$("#reportReasonModel").modal("hide");
				$("#returnException").html("");
				$("#myModalLabel").text("");
			});
			
			//取消批量操作
			$(".conal").bind("click",function(){
				$("#myReport .deleteReport").show();
				$("#myReport .eidtReport").show();
				$("#myReport .check").hide();
			});
			
//			批量保存（修改）
			$(".reportSaveAll").bind("click",function(){
				var beanArray=new Array();
				var statusArray=new Array();
					//获取选中行
				$("#myReport [name='reportCheck']:checked").each(function(){  
					var bean=new Object();
					bean.id=$(this).val();
					bean.qualified=$(this).parents().children('td').eq(9).children('input').val();//合格数
					bean.noQualified=$(this).parents().children('td').eq(10).children('input').val(); //不合格数
					bean.noQualifiedReason=$(this).parents().children('td').eq(11).children('input').val();//不合格原因
					beanArray.push(bean);
					var status=$(this).parent().parent().children("td").eq(12).children("button").eq(0).val();//状态
					if(status!=2){
						statusArray.push(status);
					}
				}); 
				if(statusArray.length>0){
					layAlert("未退回不可修改");
					return false;
				}
				if(beanArray.length<=0){
					return false;
				}
				ajaxUtil.ajaxRuquest("approval/updateReport",{"reportArrayJSONStr":JSON.stringify(beanArray)},function(data){
					reportP.returnModalShow(data);
					tableReport.ajax.reload( null, false);
				});
			});
			
//			批量删除
			$(".reportDeleteAll").bind("click",function(){
				var idArray=new Array();
				var statusArray=new Array();
				$("#myReport [name='reportCheck']:checked").each(function(){  
					idArray.push($(this).val());
					var status=$(this).parent().parent().children("td").eq(12).children("button").eq(0).val();
					if(status!=2){
						statusArray.push(status);
					}
				}); 
				if(statusArray.length>0){
					layAlert("未退回不可删除");
					return false;
				}
				if(idArray.length<=0){
					return false;
				}
					//获取选中行
				ajaxUtil.ajaxRuquest("approval/deleteAllReport",{"idArray":JSON.stringify(idArray)},function(data){
					layer.msg(data,{icon:1});
					tableReport.ajax.reload( null, false);
				});
			});
			
		},
		//获取车间名称
		getWorkshopName: function () {
			ajaxUtil.ajaxRuquest('basicData/getDeptNoMegerWorkShop', {
				"deptId": null
			}, function (data) {
				var html = "";
				for (var i = 0; i < data.length; i++) {
					html = html + "<option value='" + data[i].id + "'>" + data[i].workshopName + "</option>";
				}
				$("#workshopName").html("<option value=''>请选择</option>");
				$("#workshopName").append(html);
			});
		},
		getAllSearchWhere:function(){/**获取所有筛选条件*/
			ajaxUtil.ajaxRuquestNoQuan('companyMaterial/getAllOrderSearchWhere',null,function(data){
				reportP.orderList=data;
				filterInput.filterView("",reportP.orderPamar,reportP.orderList);
			});
		},
		getAllMachining:function(){
			ajaxUtil.ajaxRuquestNoQuan('basicData/getRowMaterialType',{"isvolid":1},function(data){
				var html="";
				for(var i=0;i<data.length;i++){
					html+="<option value='"+data[i]+"' >";
				}
				$("#machiningList").html(html);
			});
		},
		bind:function(){
			$('.qualifiedInput').unbind("keyup"); 
			$('.noQualifiedInput').unbind("keyup"); 
			$('.count').unbind("keyup"); 
			$(".qualifiedInput").bind("keyup",function(){
				var re=/^[1-9]+[0-9]*]*$/;
				var str=$(this).val();
				if(!re.test(str)){
				   str=str.substring(0,str.length-1);
				   $(this).val(str);
				   return false;
				 }
			});
			$(".noQualifiedInput").bind("keyup",function(){
				var re=/^[0-9]*]*$/;
				var str=$(this).val();
				if(!re.test(str)){
					str=str.substring(0,str.length-1);
					$(this).val(str);
					return false;
				}
			});
			
			$(".count").bind("keyup",function(){
				var re=/^[1-9]+[0-9]*]*$/;
				var str=$(this).val();
				if(!re.test(str)){
				   str=str.substring(0,str.length-1);
				   $(this).val(str);
				   return false;
				 }
			});
		},
		reportBind:function(){
			$('#myReport tbody').on('click', '.eidtReport', function () {
				var status=$(this).parent().parent().children("td").eq(12).children("button").eq(0).val();
				if(status !=2){
					layAlert("未退回不可修改");
					return false;
				}
				var text=$(this).text();
				if(text=='编辑'){
					var qualified=$(this).parents().children('td').eq(9).text();
					var noQualified=$(this).parents().children('td').eq(10).text();
					var noQualifiedReason=$(this).parents().children('td').eq(11).text();
					$(this).parents().children('td').eq(9).html("<input class='input-text qualifiedInput' type='text' value='"+qualified+"' />");
					$(this).parents().children('td').eq(10).html("<input class='input-text noQualifiedInput' type='text' value='"+noQualified+"' />");
					$(this).parents().children('td').eq(11).html("<input class='input-text noQualifiedReasonInput' type='text' value='"+noQualifiedReason+"' />");
					$(this).text("修改");
					reportP.bind();
				}
				if(text=='修改'){
					var reportArray=new Array();
					var report=new Object();
					report.id=$(this).val();
					report.qualified=$(this).parents().children('td').eq(9).children('input').val();
					report.noQualified=$(this).parents().children('td').eq(10).children('input').val();
					report.noQualifiedReason=$(this).parents().children('td').eq(11).children('input').val();
					if(report.qualified==""){
						layAlert("合格数不能为空");
						return false;
					}
					if(report.noQualified==""){
						layAlert("合格数不能为空,无则为0");
						return false;
					}
					reportArray.push(report);
					ajaxUtil.ajaxRuquest("approval/updateReport",{"reportArrayJSONStr":JSON.stringify(reportArray)},function(data){
						if(data.length<=0){
							layer.msg("修改成功",{icon:1});
						}else{
							var title=data.length+"条修改失败！"
							var html="<table>";
							for(var i=0;i<data.length;i++){
								html+="<tr><td>"+data[i].orderId+
								      "</td><td>"+data[i].machining+
								      "</td><td>"+data[i].color+
								      "</td><td><span style='color:red'>"+data[i].returnException+
								      "</span></td></tr>";
							}
							html+="</table>";
							$("#returnException").append(html);
							$("#myModalLabel").text(title);
							$("#reportReasonModel").modal("show");
						}
						tableReport.ajax.reload( null, false);
					});
				}
			});
			
			
			$('#myReport tbody').on('click', '.deleteReport', function () {
				var id=$(this).val();
				var status=$(this).parent().parent().children("td").eq(12).children("button").eq(0).val();
				if(status != 2){
					layAlert("未退回不可删除");
					return false;
				}
				ajaxUtil.ajaxRuquest("approval/deleteReport",{"id":id},function(data){
					layer.msg(data,{icon:1});
					tableReport.ajax.reload( null, false);
				});
			});
			

			/**
			 * 发起修改申请
			 */
			$("#myReport tbody").on("click",".launchUpdate",function(){
				var id=$(this).val();
				var status=$(this).parent().parent().children("td").eq(12).children("button").eq(0).val();
				if(status != 1){
					layAlert("未审核不可申请修改");
					return false;
				}
				//工序名称
				var procedure=$(this).parent().parent().children("td").eq(6).text();
				//关联源
				var releationSource=$(this).parent().parent().children("td").eq(7).text();
				if((releationSource=='退回至仓库' || releationSource=='外协' || releationSource=='成品仓' || releationSource=='待处理仓' || releationSource=='报废仓' || releationSource=='半成品')){
					layAlert("仓库与外协不可申请退回");
					return false;
				}
				ajaxUtil.ajaxRuquestNoQuan("workshop/launchUpdateReport",{"id":id},function(data){
					layer.msg(data,{icon:1});
					tableReport.ajax.reload( null, false);
				});
			});
		},
		getMyRoportNotApprovalData:function(object){
			tableReport=ajaxUtil.dataTablesAjaxNotFxiaction("myReport",10,"approval/getMyRoportData",
					object,[
					{"data":"companyOrderId"},
					{"data":"factoryId"},
					{"data":"customerId"},
					{"data":"machining"},
					{"data":"color"},
					{"data":"workShopName"},
					{"data":"procedur"},
					{"data":"relationSource"},
					{"data":"touchTime"},
					{"data":"qualified"},
					{"data":"noQualified"},
					{"data":"noQualifiedReason"},
					{"data":"status",render: function (data,type,row) {
						var str="";
						switch (data) {
			                    case 0:
			                    	if(row.firstApprovalStatus==1){
			                    		str="<button class='btn btn-warning radius' value='"+data+"'>等待二次审核</button>";
			                    	}else{
			                    		str="<button class='btn btn-warning radius' value='"+data+"'>待审核</button>";
			                    	}
			                        break;
			                    case 1:
			                    	//如果已经发起申请  
			                    	if(row.isLaunch==1){
			                    		str="<button class='btn btn-primary radius' value='"+data+"'>申请退回中</button>";
			                    	}else{
			                    		str="<button class='btn btn-secondary radius' value='"+data+"'>已审批</button>";
			                    	}
			                        break;
			                    case 2:
			                    	str="<button  class='btn btn-danger radius' value='"+data+"'>退回</button>";
			                        break;
	                           }
			            return str;
			          }},
			        {"data":"approvalUserName",render: function (data,type,row) {
			        	if(data==null || data.length<=0){
			        		return "";
			        	}
			        	var str="";
			        	for(var i=0;i<data.length;i++){
			        		str=str+' '+data[i];
			        	}
			        	return str;
			        }},
			        {"data":"auditor"},
			        {"data":"approvalReason"},
					{"data":"typeId",render: function (data,type,row) {
						if(row.status==2){
							//如果是车间交接，只能修改出库那边
							if(row.otherType==1 && row.procedur=='交接入库'){
								return "";
							}else{
								return	"<button value='"+data+"'  class='deleteReport btn btn-danger radius '>删除</button>" +
								"<input type='checkbox' name='reportCheck' value='"+data+"' hidden='hidden' class='check'>";
							}
						}else if(row.status==1 && row.isLaunch!=1 && (row.procedur!='交接入库' || row.relationSource == '无')){//如果状态是已审核并且不是申请修改状态
							return "<button class='launchUpdate btn btn-primary radius' type='button' value='"+data+"' >申请退回</button>";
						}else{
							return "";
						}
					}}
			]);
//			reportP.reportBind();
		},
//		getMyFeedOrderNotApprovalData:function(){
//			ajaxUtil.ajaxRuquest("approval/getMyFeedOrderNotApprovalData",{},function(data){
//				var html="";
//				for(var i=0;i<data.length;i++){
//					var detailList=data[i].detailList;
//					var span=detailList.length;
//					var status="未审核";
//					if(data[i].status==1){
//						status="已审核";
//					}
//					if(data[i].status==2){
//						status="退回";
//					}
//					html+="<tr><td rowspan='"+span+"'>"+data[i].orderId+
//					      "</td><td rowspan='"+span+"'>"+data[i].factoryId+
//					      "</td><td rowspan='"+span+"'>"+status+
//					      "</td><td class='materialCode'>"+detailList[0].companyMaterialTableBean.materialCode+
//					      "<input type='hidden'  value='"+detailList[0].companyMaterialTableBean.isEquals+"' class='isEquals'>"+
//					      "</td><td>"+detailList[0].companyMaterialTableBean.materialName+
//					      "</td><td>"+detailList[0].companyMaterialTableBean.model+
//					      "</td><td>"+detailList[0].companyMaterialTableBean.unit+
//					      "</td><td class='FeedCount "+data[i].id+"'>"+detailList[0].feedCount+
//					      "</td><td rowspan='"+span+"'>"+data[i].createTime+
//					      "</td><td rowspan='"+span+"'>"+data[i].createUser+
//					      "</td><td rowspan='"+span+"'>"+data[i].approvalUser+
//					      "</td><td rowspan='"+span+"'>"+data[i].approvalReason+
//					      "</td><td rowspan='"+span+"'>"+"<button class='eidtReport btn btn-secondary radius' type='button' value='"+data[i].id+"' >编辑</button><br/> " +
//														"<button value='"+data[i].id+"'  class='deleteReport btn btn-danger radius '>删除</button><br/>" +
//														"<input type='checkbox' name='reportCheck' value='"+data[i].id+"' hidden='hidden' class='check'>";
//					      "</td></tr>";
//						  for(var j=1;j<detailList.length;j++){
//							  	html+="<tr><td class='materialCode'>"+detailList[j].companyMaterialTableBean.materialCode+
//							  	"<input type='hidden'  value='"+detailList[j].companyMaterialTableBean.isEquals+"' class='isEquals'>"+
//							  	  "</td><td>"+detailList[j].companyMaterialTableBean.materialName+
//							      "</td><td>"+detailList[j].companyMaterialTableBean.model+
//							      "</td><td>"+detailList[j].companyMaterialTableBean.unit+
//							      "</td><td class='FeedCount "+data[i].id+"'>"+detailList[j].feedCount+
//							      "</td></tr>";
//						  }
//				}
//				$("#feedTable tbody").html(html);
//				reportP.tableBind("feedTable");
//			});
//		},
		returnModalShow:function(data){
			if(data.length<=0){
				layer.msg("修改成功",{icon:1});
			}else{
				var title=data.length+"条修改失败！"
				var html="<table>";
				for(var i=0;i<data.length;i++){
					html+="<tr><td>"+data[i].orderId+
					      "</td><td>"+data[i].machining+
					      "</td><td>"+data[i].color+
					      "</td><td><span style='color:red'>"+data[i].returnException+
					      "</span></td></tr>";
				}
				html+="</table>";
				$("#returnException").append(html);
				$("#myModalLabel").text(title);
				$("#reportReasonModel").modal("show");
			}
		}
}